
var http = require('../../../../service/http.js');//请求类
var util = require('../../../../utils/util.js');//工具类

const app = getApp();
var rd_session  = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //-----------页面加载--------------------------------
    showPage: false, //是否展示页面

    region:'',// '省份 城市 区县',//['省份 ', '城市 ', ' 区县'],  //初始化地区显示
    customItem: '',
    //--------------验证表单------------------
    phoneNum:'',
    isPhone:'',//是否为手机号

    //--------------调用微信接口添加地址-----------
    isFromWX: false,//是否选择了微信地址
    userName: '',//用户名
    telNumber: '',//手机号
    regionInfo: '',//地区信息
    detailInfo: '',//详细地址

    addressObj:{},//地址对象
    hasAddress:false,//是否有默认地址
    isEdit:false,//是否是编辑状态
    addressList:[],//地址列表
    aid:0,//编辑地址id
    isAdd: false,//是否是新增

    //------------表单验证提示信息----------------
    msg:'',
    //------------授权弹出层----------------------
    showSettingBox: false,//打开引导用户设置弹出层
    authorizeMsg: '',//授权信息提示
    navbackNum:0,//回退页面数量
    skipPageName:'',//从哪个页面跳转过来
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log('setAddress', options);
    //请求收货地址列表
    
    rd_session = wx.getStorageSync('rd_session');
    let defaultAddress = wx.getStorageSync('defaultAddress');
    console.log(defaultAddress);
    if (defaultAddress != '') {
      wx.setNavigationBarTitle({
        title: '选择默认收货地址'
      })
    } else {
      wx.setNavigationBarTitle({
        title: '新增收货地址'
      })
    }
    
    if (options.pageName) {
      this.setData({
        skipPageName: options.pageName
      })
    }
    console.log(this.data.hasAddress);
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.data.shopInfoTimeOut === true) { //非分享且已经过期，清除店铺信息
      console.log('店铺信息已过期，重新加载 app.checkSession()');
      app.checkSession();
    }
    this.getAddressList();
  },
  /**
   * 获取地址列表
   */
  getAddressList: function () {
    //请求收货地址列表
    http.getReq('/weixin/userDeliveredInfo/list', {
      rdSession: rd_session
    },  (res)=> {

      console.log('请求收货地址列表',res);
      let addressList = res.data;
      if (res.data.length > 0) {
        this.setData({
          addressList: addressList,
          hasAddress: true,
          showPage: true
        })
      } else {
        this.setData({
          hasAddress: false,
          showPage: true
        })
      }
    });

  },

  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value, this.data.region);
    let region = e.detail.value || '';
    if (!region){
      region = this.data.region;
    }
    this.setData({
      region: region,
      regionInfo: region
    })
  },
  chooseAddress: function () {//选择微信地址
    console.log('选择微信收货地址');
    let hasAddress = this.data.hasAddress;
    let regionInfo = '';//地区信息
    let [userName, telNumber, provinceName, cityName, countyName, detailInfo] = ['','','','','',''];
    wx.chooseAddress({
      success: (res) =>{
        console.log(res);
        let errMsg = res.errMsg;//是否选择了地址 chooseAddress:ok
        if (errMsg == 'chooseAddress:ok'){//有已经选择的地址
           userName = res.userName;//用户名
           telNumber = res.telNumber;//电话

           provinceName = res.provinceName;//省份；
           cityName = res.cityName;//市；
           countyName = res.countyName;//区；
           detailInfo = res.detailInfo;//详细地址；
           regionInfo = provinceName + ' ' + cityName + ' ' + countyName;//地区信息
          this.setData({
             userName: userName,
             telNumber: telNumber,
             regionInfo: regionInfo,
             detailInfo: detailInfo,
             isFromWX:true,
           })
           //选择后直接提交订单
          this.saveAddress();
        }
      },
      fail: (res)=> {
        console.log('获取微信地址失败');
        console.log(res)
        let errMsg = res.errMsg;
        if (errMsg == 'chooseAddress:fail auth deny'){
          this.showSettingBox();
        }
      },
     
    })
  },

  //保存地址
  saveAddress:function(e){
    console.log(e);
    console.log("保存地址");
    if(e){//获取formid
      this.getFormId(e);
    }
    this.setData({
      msg: ''
    })
    
    let regionInfo = this.data.regionInfo;//地区信息
    let addressObj = {};//用于传递后台的参数对象
    let [userName,  provinceName, cityName, countyName] = ['', '', '', ''];
    let [name, postalCode, pcc, detailInfo, telNumber,msg,id] = ['','','','','','',''];
    let requestUrl = '/weixin/userDeliveredInfo/add';//请求地址
   // let method = ''
    if(e){//提交表单保存地址
      console.log(e);
  
     // method = "add";
      name = e.detail.value.userName;//姓名
      if (e.detail.value.aid != 0 ){//编辑地址
        id = e.detail.value.aid;//编辑地址的id
        requestUrl = '/weixin/userDeliveredInfo/update'
      }
      postalCode = '';
      console.log(e.detail.value.region);
      let region = e.detail.value.region;
      if (region.length > 0 ){
        pcc = region.toString();//省市区
        console.log(pcc);
        let pccArr = [];
        if (pcc.indexOf(',') > -1){
          pccArr = pcc.split(',');
        } else if(pcc.indexOf(' ') > -1){
          console.log('空格分开');
          pccArr = pcc.split(' ');
        }
        pcc = pccArr[0] + ' ' + pccArr[1] + ' '+pccArr[2];
      }
      detailInfo = e.detail.value.detailInfo;//详细地址
      telNumber = e.detail.value.telNumber;//收货人手机号
      
      //------------填写验证信息------------------------
      if (name == ''){
        msg = '请输入收货人姓名';
      } else if (!(/^1[23456789]\d{9}$/.test(telNumber))) {
        console.log(telNumber);
        msg = '请输入正确的手机号';
      }else if (!pcc){
        console.log(pcc);
        msg = '请选择地区信息';
      }else if (detailInfo == '') {
        msg = '请输入收货人详细地址';
      } 
    }else{//通过微信接口选择提交保存地址
      name = this.data.userName;//姓名
      postalCode = '';
      pcc = regionInfo//省市区
      detailInfo = this.data.detailInfo;//详细地址
      telNumber = this.data.telNumber;//收货人手机号
    }
    //消息提示
    if (msg !== ''){//校验失败
      this.setData({
        msg: msg
      })
      return 
    }else{//保存地址信息
      addressObj.name = name;
      addressObj.postalCode = postalCode;
      addressObj.pcc = pcc;
      addressObj.detailInfo = detailInfo;
      addressObj.telNumber = telNumber;
      addressObj.id = id;
      http.getReq(requestUrl, {
        rdSession: rd_session,
        addressObj: addressObj,
      },  (res)=> {
        console.log(res);

        if (res.ret) {
          wx.setStorageSync('defaultAddress', addressObj);

          util.showToast('保存成功', 1000, 'success', function () {
            setTimeout(()=> {
              wx.navigateBack({
                delta: 1,
              })
            }, 1000)
          });
        }
      });
    
    }
  },

  selectAddress:function(e){//选择地址.将选择的地址设置未默认
    console.log(e);
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;

    let addressList = this.data.addressList;
    for(let i = 0;i < addressList.length;i++){
      addressList[i].isDefault = 0;
    }
    addressList[index].isDefault = 1;
    // 修改订单地址状态
    this.setData({
      addressList: addressList,
    })

    wx.setStorageSync('defaultAddress', addressList[index]);//默认收货地址用于订单详情页显示

    if (this.data.navbackNum < 1){
      if (this.data.skipPageName != 'user'){
        wx.navigateBack({
          delta: 1,
          success:  ()=> {
            this.setData({
              navbackNum: 1,
            })
          }
        })
      }

      http.getReq('/weixin/userDeliveredInfo/selectDefault', {
        rdSession: rd_session,
        id: id
      }, (res)=> { console.log('selectDefault',res); });
      
    }else{
      return
    }

  
    http.getReq('/weixin/userDeliveredInfo/selectDefault', {
      rdSession: rd_session,
      id: id
    },  (res)=> {console.log(res);});
  },

  editAddress:function(e){//编辑商品地址
    wx.setNavigationBarTitle({
      title: '编辑收货地址',
    });
    console.log(e);
    let index = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;//地址id
    let addressList = this.data.addressList;//选择的地址
    this.setData({
      isEdit:true,
      userName: addressList[index].name,
      region: addressList[index].pcc.trim() == '省份' ? '' : addressList[index].pcc,
      telNumber: addressList[index].telNumber,
      detailInfo: addressList[index].detailInfo,
      aid: id
    })
  },
  delAddress:function(e){
    console.log("删除地址")
    let id = e.currentTarget.dataset.id;//地址id

    http.getReq('/weixin/userDeliveredInfo/delete', {
      id: id,
      rdSession: rd_session
    },  (res) =>{
      if (res.ret) {
        util.showToast('删除成功', 1000, 'success',  ()=> {
          setTimeout( ()=> {
            wx.navigateBack({
              delta: 1,
            })
          }, 1000)
         });
      }
    });
   
  },
  addAddress:function(e){//新增地址
    console.log('新增地址');
    wx.setNavigationBarTitle({
      title: '新增地址',
    })
    this.setData({
      userName:'',
      region: this.data.region,
      telNumber: '',
      detailInfo: '',
      aid: '',
      isAdd:true
    })
  },
  getFormId: function (e) {
    console.log(e);
    app.getFormId(e);
  },
  cancelSettingBox: function () { //关闭设置提示窗
    app.cancelSettingBox();
    this.setData({
      showSettingBox: app.data.showSettingBox
    })
  },
  showSettingBox: function () {//打开设置提示窗
    app.showSettingBox();
    this.setData({
      showSettingBox: app.data.showSettingBox,
      authorizeMsg: '访问通讯地址',//授权信息提示
    })
  },

  bindopensetting:function(e){//设置授权（去设置）
    console.log(e)
    let authSetting = e.detail.authSetting['scope.address'];
    if (authSetting == true) {//同意授权
      //获取微信地址
      this.chooseAddress();
      this.cancelSettingBox();
    }
  }
})